#include "RingQueue.hpp"
#include "Task.hpp"
#include <iostream>
#include <time.h>
#include <pthread.h>
#include <unistd.h>

struct ThreadData
{
    RingQueue<Task> *_rq;
    std::string _threadName;
};

void *Consumer(void *args)
{
    ThreadData *td = static_cast<ThreadData*>(args);
    RingQueue<Task> *rq = td->_rq;
    std::string name = td->_threadName;
    
    while (true)
    {
        // 消费
        Task t;
        rq->pop(&t);
        // 计算
        t();  // t.run()
        std::cout << "Consumer get task, task is: " << t.GetTask() 
        << "who: " << name << " result: " << t.GetResult() << std::endl;
    }
    return nullptr;
}

void *Productor(void *args)
{
    ThreadData *td = static_cast<ThreadData*>(args);
    RingQueue<Task> *rq = td->_rq;
    std::string name = td->_threadName;
    int len = opers.size();

    while (true)
    {
        // 模拟生产者生产数据
        int data1 = rand() % 10 + 1; 
        usleep(10);
        int data2 = rand() % 10;
        char op = opers[rand() % len];
        Task t(data1, data2, op);

        // 生产
        rq->push(t);
        std::cout << "Productor task done, task is: " << t.GetTask() << std::endl;
        sleep(1);
    }
    return nullptr;
}

int main()
{
    srand(time(nullptr));
    RingQueue<Task> *rq = new RingQueue<Task>(50);
    std::vector<ThreadData*> tds;
    pthread_t c[3], p[5];
    for (int i = 0; i < 3; ++i)  
    {
        ThreadData *td = new ThreadData();
        td->_rq = rq;
        td->_threadName = "Productor-" + std::to_string(i);
        tds.push_back(td);
        pthread_create(c + i, nullptr, Productor, td);
    }
    for (int i = 0; i < 5; ++i)
    {
        ThreadData *td = new ThreadData();
        td->_rq = rq;
        td->_threadName = "Consumer-" + std::to_string(i);
        tds.push_back(td);
        pthread_create(c + i, nullptr, Consumer, td);
    }  

    for (int i = 0; i < 3; ++i)  pthread_join(c[i], nullptr);
    for (int i = 0; i < 5; ++i)  pthread_join(p[i], nullptr);

    for (auto td : tds) delete td;
    delete rq;

    return 0;
}
